package com.ruoyi.web.controller.wps.controller;


import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtilTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.generator.util.WordUtils;
import com.ruoyi.publish.domain.AssistInfo;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.domain.IdIdentsample;
import com.ruoyi.publish.domain.IdReport;
import com.ruoyi.publish.domain.wps.WFileT;
import com.ruoyi.publish.helper.ConfigManager;
import com.ruoyi.publish.helper.DocumentManager;
import com.ruoyi.publish.helper.FileModel;
import com.ruoyi.publish.service.*;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.web.controller.tool.StringUtilTool.detailReportCodeList;
import static com.ruoyi.web.controller.tool.StringUtilTool.numberSupplement;

@Controller
@RequestMapping("/sys/word")
public class WpsToolController {
    protected final Logger logger = LoggerFactory.getLogger(WpsToolController.class);

    private String prefix = "wps";
    @Autowired
    private IWFileTService iwFileTService;

    @Value("${ruoyi.wordPath}")
    private  String  wordBaseDirtory;

    @Value("${ruoyi.profile}")
    private String profile;

    @Value("${ruoyi.wordTempletePath}")
    private  String  wordTempletePath;

    @Value("${ruoyi.intrServerIp}")
    private  String  intrServerIp;


    @Autowired
    private IIdAcceptRegisterService idAcceptRegisterService;

    @Autowired
    private IIdIdentsampleService idIdentsampleService;

    @Autowired
    private IIdExpertService idExpertService;

    @Autowired
    private IIdReportService iIdReportService;
    /**
    * @Description: wps 查看界面
    * @Param: []
    * @return: java.lang.String
    * @Author: 张泽望
    * @Date: 2021/1/20
    */
    @GetMapping("/wpsEditor/{wFileId}")
    public String wpsEditor(@PathVariable("wFileId") Long wFileId, ModelMap mmap) {
        WFileT wFile=iwFileTService.selectWFileTById(wFileId);
        if (wFile != null) {
            mmap.put("wFileId", wFileId);
        }
        return prefix + "/wpsEditor";
    }







    //    出版物鉴定受理通知书
    @GetMapping("/accept/{id}")
    public String accept(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {


        mmap=getUserId(mmap);
        System.out.println("进入accept");

        IdAcceptRegister idAcceptRegister1=idAcceptRegisterService.selectIdAcceptRegisterById(id);
        //判断存储 字段ex3 文件名称是否存在 不存在新建，存在查看

        String dirtory="accept";
        Long wFileId=0l;



        Map<String,Object> map=new HashMap<String,Object>();
        map.put("${code}",idAcceptRegister1.getEx1());
        map.put("${sendUnit}",idAcceptRegister1.getSendUnit());
        map.put("${title}",idAcceptRegister1.getTitle());
        map.put("${documentNum}",idAcceptRegister1.getDocumentNum());
        map.put("${sendTime}", DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getSendDate()));
        map.put("${acceptTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getAcceptDate()));
        map.put("${opinion}", StringUtils.isEmpty(idAcceptRegister1.getRemark())?" ":idAcceptRegister1.getRemark());



        String templateWordFullPath=wordTempletePath+"/accept.docx";
        String newsWordPath=wordBaseDirtory+"/accept";
        if (StringUtils.isEmpty(idAcceptRegister1.getEx3())){
//             生成相应文件返回文件名称
            String fileName= WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtory);

            idAcceptRegister1.setEx3(fileName);//ex3
            idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);
            String filePathLoad="/accept"+"/"+idAcceptRegister1.getEx3()+".docx";
            String filePath=wordBaseDirtory+"/accept"+"/"+idAcceptRegister1.getEx3()+".docx";
            File file =new File(filePath);

            wFileId=InsertFile(fileName,"出版物鉴定受理通知书"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
        }else{
            String filePath=wordBaseDirtory+"/accept"+"/"+idAcceptRegister1.getEx3()+".docx";

            if (!WordUtils.checkWordFile(filePath)){
                String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtory);
                String filePathLoad="/accept"+"/"+idAcceptRegister1.getEx3()+".docx";

                idAcceptRegister1.setEx3(fileName);//ex3
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);
                File file =new File(filePath);
                wFileId=InsertFile(fileName,"出版物鉴定受理通知书"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

            }else{
                WFileT  query=new WFileT();
                query.setFileUuid(idAcceptRegister1.getEx3());
                List<WFileT>  files=iwFileTService.selectWFileTList(query);
                if (files.size()!=0){
                    wFileId=files.get(0).getId();
                }else{
                    String filePathLoad="/"+dirtory+"/"+idAcceptRegister1.getEx3()+".docx";

                    File file =new File(filePath);
                    wFileId=InsertFile(idAcceptRegister1.getEx3(),"出版物鉴定受理通知书"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

                }

            }
        }
//        WFileT filets=new WFileT();
//        filets.setFileUrl(idAcceptRegister1.getEx3());
//        List<WFileT> filess=iwFileTService.selectWFileTList(filets);
        String filePath=wordBaseDirtory+"/accept/"+idAcceptRegister1.getEx3()+".docx";
        String fileName=idAcceptRegister1.getEx3()+".docx";
        System.out.println("进入word查看编辑"+fileName);
        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }







    //    出版物鉴定登记表
    @GetMapping("/register/{id}")
    public String register(@PathVariable("id") Long id,HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        System.out.println("进入register");

        mmap=getUserId(mmap);

        IdAcceptRegister idAcceptRegister1=idAcceptRegisterService.selectIdAcceptRegisterById(id);
        //判断存储 字段ex4 文件名称是否存在 不存在新建，存在查看

//            RegisterDocument entity=new RegisterDocument();
//            entity.setCode(idAcceptRegister1.getEx1());
//            entity.setSendUnit(idAcceptRegister1.getSendUnit());//送检部门
//            entity.setTitle(idAcceptRegister1.getTitle());//标题
//            entity.setDocumentNum(idAcceptRegister1.getDocumentNum());
//            entity.setSendTime(DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getSendDate()));
//            entity.setAccpetTime(DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getAcceptDate()));
//            entity.setOpinion(idAcceptRegister1.getRemark());

        String dirtoty="register";
        Long wFileId=0L;
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("${code}",idAcceptRegister1.getEx1());
        map.put("${sendUnit}",idAcceptRegister1.getSendUnit());
//            map.put("${title}",idAcceptRegister1.getTitle());
        map.put("${documentNum}",idAcceptRegister1.getDocumentNum());
        map.put("${sendTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getSendDate()));
        map.put("${acceptTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getAcceptDate()));
        map.put("${content}",idAcceptRegister1.getIdentContent());
        map.put("${sampleType}",idAcceptRegister1.getCategory());
        map.put("${sampleNum}",idAcceptRegister1.getTypes()+"/"+String.valueOf(idAcceptRegister1.getNum()));

        String templateWordFullPath=wordTempletePath+"/register.docx";
        String newsWordPath=wordBaseDirtory+"/register";
        if (StringUtils.isEmpty(idAcceptRegister1.getEx4())){
//             生成相应文件返回文件名称
            String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
            idAcceptRegister1.setEx4(fileName);
            idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

            String filePathLoad="/register"+"/"+idAcceptRegister1.getEx4()+".docx";
            String filePath=wordBaseDirtory+"/register"+"/"+idAcceptRegister1.getEx4()+".docx";
            File file =new File(filePath);

            wFileId=InsertFile(fileName,"出版物鉴定登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
        }else{
            String filePath=wordBaseDirtory+"/register/"+idAcceptRegister1.getEx4()+".docx";
            System.out.println("文件地址="+filePath);
            if (WordUtils.checkWordFile(filePath)){
                WFileT  query=new WFileT();
                query.setFileUuid(idAcceptRegister1.getEx4());
                List<WFileT>  files=iwFileTService.selectWFileTList(query);
                if (files.size()!=0){
                    wFileId=files.get(0).getId();
                }else{
                    String filePathLoad="/"+dirtoty+"/"+idAcceptRegister1.getEx4()+".docx";

                    File file =new File(filePath);
                    wFileId=InsertFile(idAcceptRegister1.getEx4(),"出版物鉴定登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

                }
            }else{
                String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
                idAcceptRegister1.setEx4(fileName);
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

                String filePathLoad="/register"+"/"+idAcceptRegister1.getEx4()+".docx";
                File file =new File(filePath);

                wFileId=InsertFile(fileName,"出版物鉴定登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
            }
        }

        String filePath=wordBaseDirtory+"/register/"+idAcceptRegister1.getEx4()+".docx";
        System.out.println(filePath);
        String fileName=idAcceptRegister1.getEx4()+".docx";
        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }


    //    出版物鉴定登记表
    @GetMapping("/report/{id}")
    public String report(@PathVariable("id") Long id,HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        System.out.println("进入report");
        mmap=getUserId(mmap);


        IdReport idReport=iIdReportService.selectIdReportById(id);
        //判断存储 字段ex3 文件名称是否存在 不存在新建，存在查看
        IdAcceptRegister  register=idAcceptRegisterService.selectIdAcceptRegisterById(idReport.getRegisterId());
        if(idReport==null||register==null){
            return  "/error";
        }

        String directory="report";
        Long wFileId=0L;


        Map<String,Object> map=new HashMap<String,Object>();
//            map.put("${year}",DateUtils.parseDateToStr("YYYY", idReport.getCreateTime()));
        map.put("${yearCode}","〔"+DateUtils.parseDateToStr("YYYY", idReport.getCreateTime())+"〕"+numberSupplement(idReport.getBy1().split("-")[1],4)+"号");
        map.put("${sendUnitForTitle}",register.getSendUnit());
        map.put("${sendUnit}",register.getSendUnit());
        map.put("${birefCase}",idReport.getBriefCase());
        map.put("${documentNum}",register.getDocumentNum());
        map.put("${identiTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idReport.getCreateTime()));
        map.put("${content}", StringUtils.isEmpty(idReport.getIdentiContent())?" ":idReport.getIdentiContent());
        //map.put("${copyrightRecord}",StringUtils.isEmpty(idReport.getCopyrightRecord())?" ":"见附件");
        map.put("${copyrightRecordEx}",StringUtils.isEmpty(idReport.getCopyrightRecordEx())?" ":idReport.getCopyrightRecordEx());
        map.put("${ideentiSituation}",StringUtils.isEmpty(idReport.getIdentiSituation())?" ":idReport.getIdentiSituation());
        map.put("${apprCon}",StringUtils.isEmpty(idReport.getAppraCon())?" ":idReport.getAppraCon());
        //样本版权记录是否有图片
        try {
            if(!StringUtils.isEmpty(idReport.getCopyrightRecord())){
                String[] pic = idReport.getCopyrightRecord().split(",");
                ArrayList<String> picList = new ArrayList<>();
                for (int i = 0;i<pic.length;i++){
                    String substring = pic[i].substring(8);// /upload/.../..
                    picList.add(substring);
                }
                ArrayList<Map> list = new ArrayList<>();
                for (int i = 0;i<picList.size();i++){
                    HashMap<Object, Object> pictureMap = new HashMap<>();//图片参数集合
                    pictureMap.put("width", 500);
                    pictureMap.put("height", 700);
                    pictureMap.put("type", picList.get(i).split("\\.")[1]);
                    pictureMap.put("content", WordUtils.inputStream2ByteArray(new FileInputStream(profile+picList.get(i)), true));
                    list.add(pictureMap);
                }
                map.put("${copyrightRecord}",list);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        map.put("${dstr}","该社");


        System.out.println("鉴定内容"+map.get("${content}"));
        System.out.println("鉴定内容1"+idReport.getIdentiContent());
        System.out.println("鉴定内容1"+StringUtils.isEmpty(idReport.getIdentiContent()));
        System.out.println("鉴定内容2"+ StringUtilTool.isNull(idReport.getIdentiContent()));
        String idSampleas=idReport.getSampleIds();

        String templeteName="reportYes";
        String sampleNameS=" ";
        StringBuffer stringBuffer=new StringBuffer();
        System.out.println(idSampleas);
        if("正式出版物".equals(idReport.getAppraCon())){


            if (StringUtils.isNotEmpty(idSampleas)){
                String idSamplesArray[]=idSampleas.split(",");
                Long[] nums=new Long [idSamplesArray.length];
                for (int i=0;i<idSamplesArray.length;i++){
                    nums[i]=Long.parseLong(idSamplesArray[i]);
                }
                List<IdIdentsample> sampleList=idIdentsampleService.selectIdIdentsampleByIds(nums);
                List<String> names = sampleList.stream().map(p -> p.getSampleName()).collect(Collectors.toList());
                List<String> publishUnits=new ArrayList<String>();
                sampleNameS=StringUtils.join(names,"、");

                for (IdIdentsample sample:sampleList) {
                    if (StringUtils.isNotEmpty(sample.getPublishingUnit())){
                        if (!publishUnits.contains(sample.getPublishingUnit())){
                            publishUnits.add(sample.getPublishingUnit());
                        }
                    }
                }
                String publishUnit=StringUtils.join(publishUnits,"、");

                System.out.println("publishUnit"+publishUnit);


                map.put("${na}",sampleNameS);
                map.put("${naNum}",sampleNameS+"("+register.getDocumentNum()+")");
                map.put("${newn}",StringUtils.isEmpty(publishUnit)?"相关单位进一步核查，提请鉴定的"+sampleNameS+"系该社正式出版物。":publishUnit+"进一步核查，提请鉴定的"+sampleNameS+"系该社正式出版物。");
                map.put("${publishUnit}",StringUtils.isEmpty(publishUnit)?" ":publishUnit);

                System.out.println("sampleNameS"+sampleNameS);

            }


        }else if ("非法出版物".equals(idReport.getAppraCon())){
            if(StringUtils.isEmpty(idReport.getCopyrightRecord())){//若样本记录没有图片的模板
                templeteName="reportNo";
            }else{
                templeteName="reportNoA31";//若样本记录有内容的模板
            }

            IdIdentsample sample=idIdentsampleService.selectIdIdentsampleById(Long.parseLong(idReport.getSampleIds()));

            String letterOrder=sample.getLetterOrder();
            map.put("${num}",sample.getSampleCode());
            map.put("${sampleName}","《"+sample.getSampleName()+"》1册");

            map.put("${letterOrder}","系来函所附清单的序号"+(StringUtils.isEmpty(letterOrder)?" ":letterOrder));

        }else if("其他".equals(idReport.getAppraCon())){
            templeteName="reportOther";

            if (StringUtils.isNotEmpty(idSampleas)){
                String idSamplesArray[]=idSampleas.split(",");
                Long[] nums=new Long [idSamplesArray.length];
                for (int i=0;i<idSamplesArray.length;i++){
                    nums[i]=Long.parseLong(idSamplesArray[i]);
                }
                List<IdIdentsample> sampleList=idIdentsampleService.selectIdIdentsampleByIds(nums);
                List<String> publishUnits=new ArrayList<String>();

                List<String> names = sampleList.stream().map(p -> p.getSampleName()).collect(Collectors.toList());
                sampleNameS=StringUtils.join(names,"、");

                for (IdIdentsample sample:sampleList) {
                    if (StringUtils.isNotEmpty(sample.getPublishingUnit())){
                        if (!publishUnits.contains(sample.getPublishingUnit())){
                            publishUnits.add(sample.getPublishingUnit());
                        }
                    }
                }
                String publishUnit=StringUtils.join(publishUnits,"、")+"进一步核查，            。";

                System.out.println("publishUnit"+publishUnit);
                map.put("${na}",sampleNameS);
                map.put("${naNum}",sampleNameS+"("+register.getDocumentNum()+")");
                map.put("${newn}",sampleNameS);
                map.put("${publishUnit}",StringUtils.isEmpty(publishUnit)?"":publishUnit);

            }
        }


        System.out.println(map.get("${content}"));
        String templateWordFullPath=wordTempletePath+"/"+templeteName+".docx";
        String newsWordPath=wordBaseDirtory+"/"+directory;

        if (StringUtils.isEmpty(idReport.getBy2())){
//             生成相应文件返回文件名称
            logger.info("idReport.getBy2()为空，进入调用生成文档方法");
            String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,templeteName);
            logger.info("idReport.getBy2()为空---"+fileName);
            idReport.setBy2(fileName);
            iIdReportService.updateIdReport(idReport);

            String filePathLoad="/report"+"/"+idReport.getBy2()+".docx";
            String filePath=wordBaseDirtory+"/report"+"/"+idReport.getBy2()+".docx";
            File file =new File(filePath);

            wFileId=InsertFile(fileName,"出版物鉴定登记表"+idReport.getBy1(),filePathLoad,file.length());

        }else{
            String filePath=wordBaseDirtory+"/"+directory+"/"+idReport.getBy2()+".docx";
            logger.info("文件地址="+filePath);
            if (WordUtils.checkWordFile(filePath)){

                WFileT  query=new WFileT();
                query.setFileUuid(idReport.getBy2());
                List<WFileT>  files=iwFileTService.selectWFileTList(query);
                if (files.size()!=0){
                    wFileId=files.get(0).getId();
                }else{
                    String filePathLoad="/"+directory+"/"+idReport.getBy2()+".docx";

                    File file =new File(filePath);
                    wFileId=InsertFile(idReport.getBy2(),"出版物鉴定登记表"+idReport.getBy1(),filePathLoad,file.length());

                }

            }else{
                logger.info("重新生成文件=");
                String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,templeteName);
                logger.info("重新生成文件完成="+fileName);
                idReport.setBy2(fileName);
                iIdReportService.updateIdReport(idReport);

                String filePathLoad="/"+directory+"/"+idReport.getBy2()+".docx";
                File file =new File(filePath);

                wFileId=InsertFile(fileName,"出版物鉴定登记表"+idReport.getBy2(),filePathLoad,file.length());
            }
        }

        String filePath=wordBaseDirtory+"/"+directory+"/"+idReport.getBy2()+".docx";
        String fileName=idReport.getBy2()+".docx";
        System.out.println(filePath);
        System.out.println("进入word查看编辑"+fileName);

        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }


    //    鉴定签发单
    @GetMapping("/issue/{id}")
    public String Issue(@PathVariable("id") Long id,HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        System.out.println("进入Issue");
        mmap=getUserId(mmap);


        IdReport idReport=iIdReportService.selectIdReportById(id);
        //判断存储 字段ex3 文件名称是否存在 不存在新建，存在查看
        IdAcceptRegister  register=idAcceptRegisterService.selectIdAcceptRegisterById(idReport.getRegisterId());
        if(idReport==null||register==null){
            return  "/error";
        }

        String directory="issue";
        Long wFileId=0L;

        String sammples[]=idReport.getSampleIds().split(",");
        Long ids[]=new Long[sammples.length];
        for (int i=0;i<sammples.length;i++) {
            ids[i]=Long.parseLong(sammples[i]);
        }
        List<IdIdentsample> samplesList=idIdentsampleService.selectIdIdentsampleByIds(ids);
        int sampleNum=0;

        //系来函所附清单的序号
        List<String> letterOrderLists = samplesList.stream().map(p -> p.getLetterOrder()).collect(Collectors.toList());
        String letterOrders="系来函所附清单的序号"+StringUtils.join(letterOrderLists,"、"); //系来函所附清单的序号

        for (IdIdentsample sample: samplesList) {
            //现在未非必填 所以需要判断是否为空
            if (StringUtils.isNotEmpty(sample.getSampleNumber())){
                sampleNum=sampleNum+Integer.parseInt(sample.getSampleNumber());

            }

        }

        String types="";
//            StringBuffer types=new StringBuffer();
        if (sammples.length!=0){

            List<Long> sampoleids=new ArrayList<Long>();
            for (String sample:sammples) {
                sampoleids.add(Long.parseLong(sample));
            }
            Long sampleIds[] = (Long[]) sampoleids.toArray(new Long[sampoleids.size()]);
            List<IdIdentsample> samplelists=idIdentsampleService.selectIdIdentsampleByIds(sampleIds);
            List<String>  typenams=new ArrayList<String>();
            for (IdIdentsample entity: samplelists) {
                if (!typenams.contains(entity.getSampleType())){
                    typenams.add(entity.getSampleType());
                }
            }
            String typesAll=String.join(",", typenams);
            types=typesAll;
        }
        Map<String,Object> map=new HashMap<String,Object>();
//            map.put("${year}",DateUtils.parseDateToStr("YYYY", idReport.getCreateTime()));
        map.put("${code}","〔"+DateUtils.parseDateToStr("YYYY", idReport.getCreateTime())+"〕"+idReport.getBy1()+"号");
        map.put("${sendUnit}",register.getSendUnit());
        map.put("${documentNum}",register.getDocumentNum());
        map.put("${content}",StringUtils.isEmpty(idReport.getIdentiContent())?" ":idReport.getIdentiContent());
        map.put("${sampleType}",StringUtils.isEmpty(types)?" ":types);
        map.put("${sampleNum}",String.valueOf(sampleNum));

        map.put("${reportCode}","渝新监测鉴〔"+DateUtils.parseDateToStr("YYYY", idReport.getCreateTime())+"〕"+numberSupplement(idReport.getBy1().split("-")[1],4)+"号");


        map.put("${apprCon}",idReport.getAppraCon());

        map.put("${letterOrder}",letterOrders);





//            String templeteName="reportYes";
//            if ("非法出版物".equals(idReport.getAppraCon())){
//                templeteName="reportNo";
//            }
        String templateWordFullPath=wordTempletePath+"/issue.docx";
        String newsWordPath=wordBaseDirtory+"/"+directory;

        if (StringUtils.isEmpty(idReport.getIssue())){
//             生成相应文件返回文件名称
            String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,directory);
            idReport.setIssue(fileName);
            iIdReportService.updateIdReport(idReport);

            String filePathLoad="/"+directory+"/"+idReport.getIssue()+".docx";
            String filePath=wordBaseDirtory+"/"+directory+"/"+"/"+idReport.getIssue()+".docx";
            File file =new File(filePath);

            wFileId=InsertFile(fileName,"鉴定签发单"+idReport.getBy1(),filePathLoad,file.length());
        }else{
            String filePath=wordBaseDirtory+"/"+directory+"/"+idReport.getIssue()+".docx";
            System.out.println("文件地址="+filePath);
            if (WordUtils.checkWordFile(filePath)){

                WFileT  query=new WFileT();
                query.setFileUuid(idReport.getIssue());
                List<WFileT>  files=iwFileTService.selectWFileTList(query);
                if (files.size()!=0){
                    wFileId=files.get(0).getId();
                }else{
                    String filePathLoad="/"+directory+"/"+idReport.getIssue()+".docx";

                    File file =new File(filePath);
                    wFileId=InsertFile(idReport.getIssue(),"鉴定签发单"+idReport.getBy1(),filePathLoad,file.length());

                }

            }else{
                String fileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,directory);
                idReport.setIssue(fileName);
                iIdReportService.updateIdReport(idReport);

                String filePathLoad="/"+directory+"/"+idReport.getIssue()+".docx";
                File file =new File(filePath);

                wFileId=InsertFile(fileName,"鉴定签发单"+idReport.getBy1(),filePathLoad,file.length());
            }
        }

        String filePath=wordBaseDirtory+"/"+directory+"/"+idReport.getIssue()+".docx";
        String fileName=idReport.getIssue()+".docx";
        System.out.println(filePath);
        System.out.println("进入word查看编辑"+fileName);

        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }




    //    协查函 有无附件
    @GetMapping("/assist/{id}")
    public String assist(@PathVariable("id") Long id, String yesNo, HttpServletRequest request, HttpServletResponse response, ModelMap mmap, @RequestParam("ids") String ids)
    {
        System.out.println("进入assist");


        /**
         * 功能描述: 根据样本id获取样本名称
         * @Author: zhang
         * @Date: 2021/4/20 14:51
         */
        String[] sampleString = ids.split(",");
        String sampleUnits = "";
        String publishUnit ="";
        List<String>  sampleUnitsList=new ArrayList<String>();
        List<String>  publishUnitList=new ArrayList<String>();
        for (int i = 0; i < sampleString.length; i++) {

            Long sampleId = Long.parseLong(sampleString[i]);

            IdIdentsample idIdentsample = idIdentsampleService.selectIdIdentsampleById(sampleId);
            if (StringUtils.isNotEmpty(idIdentsample.getSampleName())&&!sampleUnitsList.contains(idIdentsample.getSampleName())){
                sampleUnitsList.add(idIdentsample.getSampleName());
                publishUnitList.add(idIdentsample.getPublishingUnit());
            }
        }
        if (sampleUnitsList.size()!=0){
            sampleUnits = String.join("、", sampleUnitsList);
        }
        if(publishUnitList.size()!=0){
            List<String>  list=new ArrayList<String>();
            for (int i=0;i<publishUnitList.size();i++){
                if(!list.contains(publishUnitList.get(i))){
                    if(publishUnitList.get(i)!=null){
                        list.add(publishUnitList.get(i));
                    }
                }
            }
            publishUnit = String.join("、", list);
        }

        mmap=getUserId(mmap);


        IdAcceptRegister idAcceptRegister1=idAcceptRegisterService.selectIdAcceptRegisterById(id);

//            if (idAcceptRegister1!=null||idAcceptRegister1.getId()!=null){
//                return  "500";
//            }
//        IdIdentsample sample=new IdIdentsample();
//        sample.setRegisterId(idAcceptRegister1.getId());
//        List<IdIdentsample>  samplesList=idIdentsampleService.selectIdIdentsampleList(sample);
//        String publishUnits=" ";
//        List<String>  units=new ArrayList<String>();
//        if (samplesList.size()!=0){
//            for (IdIdentsample entity: samplesList) {
//                if(StringUtils.isNotEmpty(entity.getPublishingUnit())&&!units.contains(entity.getPublishingUnit())){
//                    units.add(entity.getPublishingUnit());
//                }
//
//            }
//        }
//
//        if (units.size()!=0){
//            publishUnits=String.join("、",units);
//        }
        String dirtoty="assist";
        Long wFileId=0l;

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("${yearCode}","〔"+DateUtils.parseDateToStr("YYYY", idAcceptRegister1.getCreateTime())+"〕"+numberSupplement(idAcceptRegister1.getEx1().split("-")[1],4)+"号");
        map.put("${sendUnit}",idAcceptRegister1.getSendUnit());
//            map.put("${title}",idAcceptRegister1.getTitle());
        map.put("${acceptTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getAcceptDate()));
        map.put("${content}",idAcceptRegister1.getIdentContent());
        map.put("${sampleType}",idAcceptRegister1.getCategory());
        map.put("${sampleNum}",String.valueOf(idAcceptRegister1.getNum()));
//        map.put("${sampleName}",String.valueOf(idAcceptRegister1.getDocumentNum()));
        map.put("${sampleName}",sampleUnits);
        map.put("${publishUnit}",publishUnit);

        String assistType = "0";//无附件协查函
        String templeteName="assist";
        if("yes".equals(yesNo)){
            templeteName="assistFile";
            assistType="1";//有附件协查函
        }

        AssistInfo assistInfo = idAcceptRegisterService.findAssistInfo(ids,assistType);//查询协查函信息


        String templateWordFullPath=wordTempletePath+"/"+templeteName+".docx";
        String newsWordPath=wordBaseDirtory+"/"+dirtoty;
        String filePath="";
        String fileName="";
        if(assistInfo!=null){
            filePath=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo.getWordName()+".docx";
            System.out.println(filePath);
            fileName=assistInfo.getWordName()+".docx";
        }
        AssistInfo assistInfo1 = new AssistInfo();
        if(!"yes".equals(yesNo)){

            if (assistInfo == null){//协查函信息为空则生成新的文档
//             生成相应文件返回文件名称
                String assistfileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
                //调整版-保存协查函信息
                assistInfo1.setWordName(assistfileName);
                assistInfo1.setSampleIds(ids);
                assistInfo1.setAssistType("0");
                assistInfo1.setRegisterId(id);
                assistInfo1.setCreateTime(DateUtils.getNowDate());
                idAcceptRegisterService.insertAssistInfo(assistInfo1);//添加最新生成的协查函信息
                String filePathLoad="/"+dirtoty+"/"+assistInfo1.getWordName()+".docx";
                String fileInfo=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo1.getWordName()+".docx";
                //初版-协查函字段
                idAcceptRegister1.setEx5(assistfileName);
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);
//
//                String filePathLoad="/"+dirtoty+"/"+idAcceptRegister1.getEx5()+".docx";
//                String fileInfo=wordBaseDirtory+"/"+dirtoty+"/"+"/"+idAcceptRegister1.getEx5()+".docx";
                File file =new File(fileInfo);

                wFileId=InsertFile(assistfileName,"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
            }else{
                String assistfilePath=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo.getWordName()+".docx";
                System.out.println("文件地址="+assistfilePath);
                if (WordUtils.checkWordFile(assistfilePath)){

                    WFileT  query=new WFileT();
                    query.setFileUuid(assistInfo.getWordName());
                    List<WFileT>  files=iwFileTService.selectWFileTList(query);
                    if (files.size()!=0){
                        wFileId=files.get(0).getId();
                    }else{
                        String filePathLoad="/"+dirtoty+"/"+assistInfo.getWordName()+".docx";

                        File file =new File(filePath);
                        wFileId=InsertFile(assistInfo.getWordName(),"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

                    }

                }else{
                    String assistfileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
                    assistInfo.setWordName(assistfileName);
                    idAcceptRegisterService.updateAssistInfo(assistInfo);
                    //初版-协查函字段
                    idAcceptRegister1.setEx5(assistfileName);
                    idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

                    String filePathLoad="/"+dirtoty+"/"+assistInfo.getWordName()+".docx";
                    String fileInfo=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo.getWordName()+".docx";

                    File file =new File(fileInfo);

                    wFileId=InsertFile(assistfileName,"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
                }
            }
            if(assistInfo1!=null){
                filePath=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo1.getWordName()+".docx";
                System.out.println(filePath);
                fileName=assistInfo1.getWordName()+".docx";
            }

        }else{

            //协查函 有附件
            if (assistInfo==null){
//             生成相应文件返回文件名称
                String assistFileFileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
                //调整版-保存协查函信息
                assistInfo1.setWordName(assistFileFileName);
                assistInfo1.setSampleIds(ids);
                assistInfo1.setAssistType("1");
                assistInfo1.setRegisterId(id);
                assistInfo1.setCreateTime(DateUtils.getNowDate());
                idAcceptRegisterService.insertAssistInfo(assistInfo1);
                //初版--有附件协查函字段
                idAcceptRegister1.setAssistFile(assistFileFileName);
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

                String filePathLoad="/"+dirtoty+"/"+assistInfo1.getWordName()+".docx";
                filePath=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo1.getWordName()+".docx";

                File file =new File(filePath);
                wFileId=InsertFile(assistFileFileName,"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
            }else{
                String assistFileFilePath=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo.getWordName()+".docx";
                System.out.println("文件地址="+assistFileFilePath);
                if (WordUtils.checkWordFile(assistFileFilePath)){
                    WFileT  query=new WFileT();
                    query.setFileUuid(assistInfo.getWordName());
                    List<WFileT>  files=iwFileTService.selectWFileTList(query);
                    if (files.size()!=0){
                        wFileId=files.get(0).getId();
                    }else{
                        String filePathLoad="/"+dirtoty+"/"+assistInfo.getWordName()+".docx";

                        File file =new File(filePath);
                        wFileId=InsertFile(idAcceptRegister1.getAssistFile(),"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

                    }
                }else{
                    String assistFileName=WordUtils.createWord3(templateWordFullPath,newsWordPath,map,dirtoty);
                    assistInfo.setWordName(assistFileName);
                    idAcceptRegisterService.updateAssistInfo(assistInfo);
                    idAcceptRegister1.setAssistFile(assistFileName);
                    idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

                    String filePathLoad="/"+dirtoty+"/"+assistInfo.getWordName()+".docx";
                    String FilePathInfo=wordBaseDirtory+"/"+dirtoty+"/"+assistInfo.getWordName()+".docx";

                    File file =new File(FilePathInfo);

                    wFileId=InsertFile(assistFileName,"协查函"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
                }
            }


//            filePath=wordBaseDirtory+"/"+dirtoty+"/"+idAcceptRegister1.getAssistFile()+".docx";
//            System.out.println(filePath);
//            fileName=idAcceptRegister1.getAssistFile()+".docx";
        }

        //确认生成协查函之后，设置样本已参与生成，不可再用于生成协查函
        for (int i = 0; i < sampleString.length; i++) {
            Long sampleId = Long.parseLong(sampleString[i]);
            IdIdentsample idIdentsample = idIdentsampleService.selectIdIdentsampleById(sampleId);
            idIdentsample.setBy3("1");
            idIdentsampleService.updateIdIdentsample(idIdentsample);
        }

        System.out.println("进入word查看编辑"+fileName);


        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }

    /**
     * 查询样本参与生成的协查函
     * @param id
     * @return
     */
    @GetMapping("/queryAssist")
    public String queryAssist(@RequestParam("id") String id,ModelMap mmap){
        AssistInfo assistInfo = idAcceptRegisterService.queryAssist(id);
        mmap = getUserId(mmap);
        Long wFileId=0l;
        if(assistInfo!=null){
            WFileT  query=new WFileT();
            query.setFileUuid(assistInfo.getWordName());
            List<WFileT>  files=iwFileTService.selectWFileTList(query);
            if(files.size()!=0){
                wFileId = files.get(0).getId();
            }
            mmap.put("wFileId", wFileId);
        }
        return prefix + "/wpsEditor";
    }



    //    送达登记表
    @GetMapping("/deliver/{id}")
    public String deliver(@PathVariable("id") Long id,HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        System.out.println("deliver");
        mmap=getUserId(mmap);




        IdAcceptRegister idAcceptRegister1=idAcceptRegisterService.selectIdAcceptRegisterById(id);


        String dirtoty="deliver";

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("${yearCode}","〔"+DateUtils.parseDateToStr("YYYY", idAcceptRegister1.getCreateTime())+"〕"+numberSupplement(idAcceptRegister1.getEx1().split("-")[1],4)+"号");
        map.put("${sendUnit}",idAcceptRegister1.getSendUnit());
        map.put("${documentNum}",idAcceptRegister1.getDocumentNum());
        map.put("${acceptTime}",DateUtils.parseDateToStr("YYYY年MM月dd日",idAcceptRegister1.getAcceptDate()));
        map.put("${content}",idAcceptRegister1.getIdentContent());
        map.put("${sampleType}",idAcceptRegister1.getCategory());
        map.put("${sampleName}",String.valueOf(idAcceptRegister1.getDocumentNum()));

        map.put("${code}",idAcceptRegister1.getEx1());


        IdReport idReport=new IdReport();
        idReport.setRegisterId(id);
        List<IdReport>  idReports=iIdReportService.selectIdReportList(idReport);
        List<String>  reports=new ArrayList<String>();
//            for (int i = 0; i < idReports.size(); i++) {
//                if (Integer.parseInt()idReports.get(i).getBy1().split("-")[1])
//            }

        String year =idAcceptRegister1.getEx1().split("-")[0];
        //不同年 区分

        List<String>  codelist=new ArrayList<>();
        for (IdReport report:idReports) {

            codelist.add(report.getBy1());
        }
        reports= detailReportCodeList(codelist);

        if (idReports.size()!=0){
//            map.put("${reportCode}",String.join("、",reports));

            map.put("${sampleNum}",String.valueOf(idReports.size())+"份");

        }else{
//            map.put("${reportCode}"," ");
            map.put("${sampleNum}","0份");

        }


        String templeteName="deliver";
        Long wFileId=0l;


        String templateWordFullPath=wordTempletePath+"/"+templeteName+".docx";
        String newsWordPath=wordBaseDirtory+"/"+dirtoty;
        if (StringUtils.isEmpty(idAcceptRegister1.getDeliver())){
//             生成相应文件返回文件名称
            String fileName=WordUtils.createWordContineTable(templateWordFullPath,newsWordPath,map,reports,dirtoty);

            idAcceptRegister1.setDeliver(fileName);
            idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);
            String filePathLoad="/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";
            String FilePathInfo=wordBaseDirtory+"/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";

            File file =new File(FilePathInfo);

            wFileId=InsertFile(fileName,"送达登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
        }else{
            String filePath=wordBaseDirtory+"/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";
            System.out.println("文件地址="+filePath);
            if (WordUtils.checkWordFile(filePath)){
                WFileT  query=new WFileT();
                query.setFileUuid(idAcceptRegister1.getDeliver());
                List<WFileT>  files=iwFileTService.selectWFileTList(query);
                if (files.size()!=0){
                    wFileId=files.get(0).getId();
                }else{
                    String filePathLoad="/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";

                    File file =new File(filePath);
                    wFileId=InsertFile(idAcceptRegister1.getDeliver(),"送达登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());

                }
            }else{
                String fileName=WordUtils.createWordContineTable(templateWordFullPath,newsWordPath,map,reports,dirtoty);
                idAcceptRegister1.setDeliver(fileName);
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister1);

                String filePathLoad="/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";
                String FilePathInfo=wordBaseDirtory+"/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";

                File file =new File(FilePathInfo);

                wFileId=InsertFile(fileName,"送达登记表"+idAcceptRegister1.getEx1(),filePathLoad,file.length());
            }
        }

        String filePath=wordBaseDirtory+"/"+dirtoty+"/"+idAcceptRegister1.getDeliver()+".docx";
        System.out.println(filePath);
        String fileName=idAcceptRegister1.getDeliver()+".docx";

        System.out.println("进入word查看编辑"+fileName);


        mmap.put("wFileId", wFileId);

        System.out.println("进入相应界面");
        return prefix + "/wpsEditor";
    }





 Long InsertFile(String id,String fileName,String fileUrl,Long fileSize){
    WFileT wFileT=new WFileT();
//    wFileT.setId(id);
    wFileT.setVersion(1L);
    wFileT.setName(fileName);
    wFileT.setFileUrl(fileUrl);
    wFileT.setCreator("1");
    wFileT.setSize(fileSize);
    wFileT.setFileUuid(id);
    iwFileTService.insertWFileT(wFileT);

     System.out.println("wpsFile ID="+wFileT.getId());
     return  wFileT.getId();
}


// 带入当前用户id
public  ModelMap getUserId(ModelMap mmap){
    String id=String.valueOf(ShiroUtils.getSysUser().getUserId());
    mmap.put("tokenId",id);
    return  mmap;

}

}
